package com.example.xd.model_permission;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.telecom.TelecomManager;
import android.util.Log;
import android.widget.Toast;

import static android.content.Context.TELECOM_SERVICE;

/**
 * @auther XuDan on 2019/5/7.
 */
public class DefaultCallPermission {
    private static DefaultCallPermission instance = null;
    private Context context;

    private DefaultCallPermission(Context context) {
        this.context = context;
    }

    public static synchronized DefaultCallPermission getInstance(Context context) {
        if (instance == null) {
            instance = new DefaultCallPermission(context);
        }
        return instance;
    }

    public void setDefaultPhoneCall() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            if (isDefaultPhoneCallApp()) {
                Log.i("xd----", "已设置默认通话");
            } else {
                Log.i("xd----", "未设置默认通话");
                Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER);
                intent.putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
                        context.getPackageName());
                context.startActivity(intent);
            }
        } else {
            context.startActivity(new Intent("android.settings.MANAGE_DEFAULT_APPS_SETTINGS"));
            Toast.makeText(context, "版本太低，不支持默认通话应用", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Android M 以上检查是否是系统默认电话应用
     */
    public boolean isDefaultPhoneCallApp() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            TelecomManager manger = (TelecomManager) context.getSystemService(TELECOM_SERVICE);
            if (manger != null) {
                String name = manger.getDefaultDialerPackage();
                return name.equals(context.getPackageName());
            }
        }
        return false;
    }
}
